package com.zzl.redis;

import com.zzl.redis.config.RedisPoolConfig;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.*;

import java.util.Set;

public class JedisUtil {


    /**
     * 单个jedis连接
     * @param jedisShardInfo
     * @return
     */
    public static Jedis getSingleJedis(JedisShardInfo jedisShardInfo){
        Jedis jedis = new Jedis(jedisShardInfo);
        return jedis;
    }

    /**
     * jedis 集群
     * @param hostAndPortList
     * @return
     */
    public static JedisCluster getJedisCluster(Set<HostAndPort> hostAndPortList,GenericObjectPoolConfig poolConfig){
        JedisCluster jedisCluster = new JedisCluster(hostAndPortList,2000, 5,poolConfig);
        return jedisCluster;
    }

    /**
     * jedis 连接池
     * @param config
     * @return
     */
    public static JedisPool getJedisPool(RedisPoolConfig config){
        JedisPool jedisPool = null;
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(config.getMaxIdle());
        jedisPoolConfig.setMaxTotal(config.getMaxActive());
        jedisPoolConfig.setTestOnBorrow(config.isTestOnBorrow());
        if(null == config.getAuth() || "".equals(config.getAuth().trim())){
            jedisPool = new JedisPool(jedisPoolConfig, config.getAddr(), config.getPort(), config.getTimeOut());
        }else{
            jedisPool = new JedisPool(jedisPoolConfig, config.getAddr(), config.getPort(), config.getTimeOut(),config.getAuth());
        }
        return jedisPool;
    }
    /**
     * 获取Jedis实例
     * @return
     */
    public synchronized static Jedis getJedis(JedisPool jedisPool) {
        Jedis resource = jedisPool.getResource();
        return resource;
    }
    /**
     * 释放jedis资源
     * @param jedis
     */
    public static void returnResource(JedisPool jedisPool,final Jedis jedis) {
        if (jedis != null) {
            jedisPool.returnResource(jedis);
        }
    }


}
